//
//  AuthenPhotoLargeVM.swift
//  kxf
//
//  Created by Mac on 2024/3/8.
//

import Foundation
import UIKit
import Photos
import MCToast

class AuthenPhotoLargeVM: UIView {
    
    let selfHeight = kFitWidth(248)
    
    var isRead = false
    var controller = WHBaseViewVC()
    
    var photoBlock:(()->())?
    var exampleBlock:(()->())?
    var saveBlock:(()->())?

    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: frame.origin.x, y: frame.origin.y, width: SCREEN_WIDHT, height: selfHeight))
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var imgView : UIImageView = {
        let img = UIImageView()
        img.layer.cornerRadius = kFitWidth(12)
        img.contentMode = .scaleAspectFit
        img.clipsToBounds = true
        img.isUserInteractionEnabled = true
        img.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.08)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(photoTapAction))
        img.addGestureRecognizer(tap)
        
        return img
    }()
    lazy var addIconImg : UIImageView = {
        let img = UIImageView()
        img.image = UIImage.init(named: "authen_photo_add")
        img.isUserInteractionEnabled = true
        
        return img
    }()
    lazy var titleLabel : UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 14, weight: .medium)
        lab.textAlignment = .center
        lab.adjustsFontSizeToFitWidth = true
        return lab
    }()
    lazy var exampleImgView : UIImageView = {
        let img = UIImageView()
        img.image = UIImage.init(named: "authen_example_icon")
        //authen_save_icon
        return img
    }()
    lazy var exampleLabel : UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 12, weight: .medium)
        lab.text = "查看示例"
        
        return lab
    }()
    lazy var exampleTapView : UIView = {
        let vi = UIView()
        vi.backgroundColor = .clear
        vi.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(exampleTapAction))
        vi.addGestureRecognizer(tap)
        
        return vi
    }()
}

extension AuthenPhotoLargeVM{
    @objc func photoTapAction() {
        if self.photoBlock != nil{
            self.photoBlock!()
        }
    }
    @objc func exampleTapAction() {
        if self.isRead == true{
//            if self.saveBlock != nil{
//                self.saveBlock!()
//            }
            self.saveAction()
        }else{
            if self.exampleBlock != nil{
                self.exampleBlock!()
            }
        }
    }
    func setImgUrl(urlstring:String){
        if urlstring.count > 5 {
            self.addIconImg.isHidden = true
            self.titleLabel.isHidden = true
            self.imgView.setImgUrl(urlString: urlstring)
        }
    }
    func setReadMode() {
        self.isRead = true
        exampleImgView.setImgLocal(imgName: "authen_save_icon")
        exampleLabel.text = "保存到相册"
        imgView.isUserInteractionEnabled = false
    }
}

extension AuthenPhotoLargeVM{
    @objc func saveAction() {
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied{
                    self.controller.presentAlertVc(confirmBtn: "打开", message: "无访问相册权限，是否去打开权限?", title: "提示", cancelBtn: "取消", handler: { (actions) in
                        let url = NSURL.init(string: UIApplication.openSettingsURLString)
                        if UIApplication.shared.canOpenURL(url! as URL){
                            UIApplication.shared.openURL(url! as URL)
                        }
                    }, viewController: self.controller)
                }else{
                    MCToast.mc_loading(autoClearTime: 30)
                    let image = self.imgView.image
                    UIImageWriteToSavedPhotosAlbum(image ?? self.imgView.mc_makeImage(), self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
        MCToast.mc_remove()
        if error != nil{
            MCToast.mc_text("保存失败。")
        }else{
            MCToast.mc_text("已保存到系统相册")
        }
    }
}
extension AuthenPhotoLargeVM{
    func initUI() {
        addSubview(imgView)
        imgView.addSubview(addIconImg)
        imgView.addSubview(titleLabel)
        addSubview(exampleLabel)
        addSubview(exampleImgView)
        addSubview(exampleTapView)
        
        setConstrait()
    }
    func setConstrait() {
        imgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(20))
            make.width.equalTo(kFitWidth(345))
            make.height.equalTo(kFitWidth(177))
        }
        addIconImg.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(10))
            make.width.height.equalTo(kFitWidth(120))
        }
        titleLabel.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
            make.bottom.equalTo(kFitWidth(-24))
            make.left.width.equalToSuperview()
        }
        exampleImgView.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(133))
            make.width.height.equalTo(kFitWidth(22))
            make.top.equalTo(imgView.snp.bottom).offset(kFitWidth(12))
        }
        exampleLabel.snp.makeConstraints { make in
            make.centerY.lessThanOrEqualTo(exampleImgView)
            make.left.equalTo(exampleImgView.snp.right).offset(kFitWidth(3))
        }
        exampleTapView.snp.makeConstraints { make in
            make.left.equalTo(exampleImgView).offset(kFitWidth(-20))
            make.right.equalTo(exampleLabel).offset(kFitWidth(20))
            make.top.equalTo(imgView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
}
